<template>
  <el-card class="userinfo-container">
    <!-- 面板屑导航 -->
    <el-breadcrumb separator="/" style="margin-bottom: 40px">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人中心</el-breadcrumb-item>
      <el-breadcrumb-item>基本资料</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form
      :model="infoForm"
      :rules="infoRuels"
      ref="infoRef"
      label-width="100px"
    >
      <el-form-item label="登录名称">
        <el-input v-model="infoForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="infoForm.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="infoForm.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="update">提交修改</el-button>
        <el-button @click="resetInfo">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import { mapState, mapActions } from 'vuex'
import { updateUserInfo } from '@/api/user'
export default {
  name: 'UserInfo',
  computed: {
    ...mapState('user', ['userInfo'])
  },
  async created () {
    await this.getUserInfo() // ajax => mutations => userInfo有值
    this.infoForm = { ...this.userInfo }
  },
  methods: {
    ...mapActions('user', ['getUserInfo']),
    // 重置
    resetInfo () {
      // TODO
      // infoForm => 三个输入框绑定的数据
      this.infoForm = { ...this.userInfo }
    },

    // 更新
    update () {
      this.$refs.infoRef.validate(async valid => {
        if (!valid) return
        const { data: { code, message } } = await updateUserInfo(this.infoForm)
        if (code !== 0) return this.$message.error(message)
        this.$message.success(message)
        this.getUserInfo()
      })
    }
  },
  data () {
    return {
      // 表单信息对象
      infoForm: {},
      // 验证规则对象
      infoRuels: {
        nickname: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            pattern: /^\S{1,10}$/,
            message: '昵称必须是1-10位的非空字符串',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            pattern: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
            message: '邮箱格式不正确',
            trigger: 'blur'
          }
        ]
      }
    }
  }
}
</script>
